// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

app.use(express.static('public'));

// 在线用户表：{ username: ws }
const users = new Map();

// 工具：广播给所有人
function broadcast(type, payload) {
  const msg = JSON.stringify({ type, payload });
  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) client.send(msg);
  });
}

// 工具：发消息给指定用户
function sendTo(username, type, payload) {
  const client = users.get(username);
  if (client && client.readyState === WebSocket.OPEN) {
    client.send(JSON.stringify({ type, payload }));
  }
}

// 新客户端连入
wss.on('connection', ws => {
  let username = null;

  // ❌ 不再发送历史消息
  // ❌ 不再读取数据库

  // 处理消息
  ws.on('message', raw => {
    try {
      const { type, payload } = JSON.parse(raw);

      if (type === 'login') {
        username = payload;
        users.set(username, ws);
        broadcast('onlineList', [...users.keys()]);
        return;
      }

      if (type === 'chat') {
        const { text } = payload;

        // 私聊指令：/w 目标 内容
        const whisper = text.match(/^\/w (\S+)\s+(.+)$/);
        if (whisper) {
          const [_, toUser, content] = whisper;
          const msgObj = { from: username, content, private: true };
          sendTo(toUser, 'chat', msgObj);
          sendTo(username, 'chat', msgObj);
        } else {
          // 普通消息（只广播，不存库）
          const msgObj = { from: username, content: text };
          broadcast('chat', msgObj);
        }
      }
    } catch (e) {
      console.error('消息格式错误', e);
    }
  });

  // 断开
  ws.on('close', () => {
    if (username) {
      users.delete(username);
      broadcast('onlineList', [...users.keys()]);
    }
  });
});

server.listen(3000, () => {
  console.log('🚀 服务器 http://localhost:3000');
});